<html>
    <head>
        <title>Products</title>
        <link href="style.css" rel="stylesheet" type="text/css" media="screen" />
    </head>
    <body>
        <div id="logo">
            <h1><a href="#">Products</a></h1>
        </div>
        <div id='info' name='info'>
            <form onsubmit="handleSubmit(); return false;">
                <div class='field'>
                    UPC:<input type='text' id='upc' name='upc' value='upc'>
                </div>
                <div class='field'>
                    Description:<input type='text' id='description' name='description'>
                </div>
                <div class='field'>
                    Brand:<input type='text' id='brand' name='brand'>
                </div>
                <div class='field'>
                    Model:<input type='text' id='model' name='model'>
                </div>
                <div class='field'>
                    Type:<a href='./productTypes.html'>[+]</a>
                    <span id='ptypespan' name='ptypespan'></span>
                </div>
                <div class='field'>
                    Quantity:<input type='button' style='width:18px;' id='delqty' onclick='AddOne("quantity",-1);' value='-' /><input type='button' id='addqty' value='+' style='width:18px;' onclick='AddOne("quantity",1);'/><input type='text' style='width:50px;' id='quantity' name='quantity'>
                </div>
                <div class='field'>
                    Ordered:<input type='button' style='width:18px;' id='delqty' onclick='AddOne("ordered",-1);' value='-' /><input type='button' id='addqty' value='+' style='width:18px;' onclick='AddOne("ordered",1);'/><input type='text' style='width:50px;' id='ordered' name='ordered'>
                </div>
                <div class='field'>
                    Cost:<input type='text' id='cost' name='cost'>
                </div>
                <div class='field'>
                    Price:<input type='text' id='price' name='price'>
                </div>
                <div class='field'>
                    <input type='button' value='Save' onclick='Save()'/>
                </div>
                <br/>
                <div class='field'>
                    Search?:<input type='text' id='searcht' name='searcht'>
                </div>
                <div class='field'>
                    <input type='button' class='buttons' value='Search' onclick='Search(document.all.searcht.value);'/>
                </div>
                <div class='field'>
                    Load?:<input type='text' id='pid' name='pid'>
                </div>
                <div class='field'>
                    <input type='button' value='Load' onclick='Load()'/>
                </div>
            </form>
        </div><span id="status">&nbsp;</span>
        <!-- ====================================== -->
        <!-- End HTML code.  Begin JavaScript code. -->
        <script type="text/javascript" src="gears_init.js">
        </script>
        <!--<script type="text/javascript" src="sample.js">
        </script>-->
        <xml id="xmlTitles" src="./products.xml?root='products'">
        </xml>
        <script>
            
            //LoadXPIE();
            
            var query = location.search;
            var itemid = query.substring(query.indexOf("id=") + 3, query.length);
            if (itemid != '') {
                Load(itemid);
            }
            
            init();
            
            
            // Open this page's local database.
            function init(){
                var success = false;
                
                if (window.google && google.gears) {
                    try {
                        db = google.gears.factory.create('beta.database');
                        
                        if (db) {
                            db.open('database-demo');
                            db.execute('create table if not exists Product' +
                            ' (id int primarykey,' +
                            ' UPC text,' +
                            ' description text,' +
                            ' brand text,' +
                            ' model text,' +
                            ' type text,' +
                            ' quantity real,' +
                            ' ordered real,' +
                            ' cost real,' +
                            ' price text' +
                            ')');
                            
                            success = true;
                            // Initialize the UI at startup.
                            
                            displayRecentPhrases();
                            loadProductTypes('');
                        }
                        
                    } 
                    catch (ex) {
                        setError('Could not create database: ' + ex.message);
                        alert('Could not create database: ' + ex.message);
                    }
                }
                
                // Enable or disable UI elements
                
                var inputs = document.forms[0].elements;
                for (var i = 0, el; el = inputs[i]; i++) {
                    el.disabled = !success;
                }
                
            }
            
            function loadXMLDoc(dname){
                //var xmlDoc;
                var xmlHttpReq = false;
                try {
                    xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
                } 
                catch (err) {
                    try {
                        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
                    } 
                    catch (err2) {
                    }
                }
                // Specify HTTP Method as POST so that we can upload large amounts of text
                xmlHttpReq.open('POST', dname, true);
                xmlHttpReq.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
                xmlHttpReq.onreadystatechange = function(){
                    if (xmlHttpReq.readyState == 4) {
                        alert('yes');
                        //alert(xmlHttpReq.responseXML.getElementsByTagName('Products')[0].text);
                    }
                }
            }
            
            void function loadTitle2(){
                // if (cboTitle.value == "0") {
                // alert("Select a title in the list!");
                // return;
                //}
                return;
                var root = xmlTitles.documentElement;
                alert('Lets sum!');
                // var listTitles =  root.selectNodes("//description[contains(. ,'Cuen')]");  //here we specify column name
                var listTitles = root.selectNodes("//priceA");
                
                
                alert('node ready:' + root.sum(listTitles));
                //nodeTitle = listTitles.sum();  //here we specify item index
                // alert(listTitles.selectSingleNode("/priceA[sum()]"));
                return;
                
                
                //var nodeTitle =  root.selectSingleNode("//titles[@title_id=\"" +
                //               cboTitle.value + "\"]");
                
                var nodeTitle = root.selectSingleNode("//products[@productid=\"" +
                searchT.value +
                "\"]");
                alert(nodeTitle.selectSingleNode("//productid").text);
                
                /*divTitleName.innerHTML = "<font color=\"blue\">" +
                
                
                 
                
                
                 
                
                
                 nodeTitle.attributes.getNamedItem("title").value + "</font>";
                
                
                 */
                
                
            }
            
            
            function Save(){
                if (!google.gears.factory || !db) {
                    return;
                }
                
                var upcT = document.all.upc;
                var descriptionT = document.all.description;
                var brandT = document.all.brand;
                var modelT = document.all.model;
                var typeT = document.all.type;
                var quantityT = document.all.quantity;
                var orderedT = document.all.ordered;
                var costT = document.all.cost;
                var priceT = document.all.price;
                
                var upc = upcT.value;
                var description = descriptionT.value;
                var brand = brandT.value;
                var model = modelT.value;
                var type = typeT.value;
                var quantity = quantityT.value;
                var ordered = orderedT.value;
                var cost = costT.value;
                var price = priceT.value;
                var currTime = new Date().getTime();
                
                //get the new id
                var rs = db.execute('select max(id)+1 as pid from product');
                var newid = 0;
                while (rs.isValidRow()) {
                    newid = rs.field(0);
                }
                
                // Insert the new item.
                // The Gears database automatically escapes/unescapes inserted values.
                db.execute('insert into Product (id, upc, description, brand, model, type, quantity, ordered, cost, price) values (?,?,?,?,?,?,?,?,?,?)', [upc, description, brand, model, type, quantity, ordered, cost, price]);
                alert('Product added.');
                // Update the UI.
                //elm.value = '';
                //displayRecentPhrases();
            }
            
            function displayRecentPhrases(){
                var recentPhrases = ['', '', ''];
                
                // Get the 3 most recent entries. Delete any others.
                var rs = db.execute('select * from product order by 1 desc');
                var index = 0;
                while (rs.isValidRow()) {
                    if (index < 3) {
                        recentPhrases[index] = rs.field(0) + '-' + rs.field(1);
                    }
                    else {
                        alert('Nothing');//db.execute('delete from customer where Timestamp=?', [rs.field(1)]);
                    }
                    ++index;
                    rs.next();
                }
                rs.close();
                
                var status = getElementById('status');
                status.innerHTML = '';
                for (var i = 0; i < recentPhrases.length; ++i) {
                    var id = 'phrase' + i;
                    status.innerHTML += '<span id="' + id + '"></span><br>';
                    var bullet = '(' + (i + 1) + ') ';
                    setTextContent(document.all.id, bullet + recentPhrases[i]);
                }
            }
            
            function Search(search){
                //alert('In search!');
                document.all.info.style.display = 'none';
                var recentPhrases = ['', '', ''];
                var query = 'select * from product where UPC like "' + search + '%"';
                query += ' OR description like "' + search + '%"';
                query += ' OR brand like "' + search + '%"';
                query += ' OR model like "' + search + '%"';
                //query += ' OR [type] like "' + search+ '%"';
                
                //alert(query);
                
                var status = document.all.status;
                status.innerHTML = '';//'Searching...' ;
                var root = xmlTitles.documentElement;
                //oXMLDoc.selectSingleNode("//EXAMPLE/CUSTOMER[contains(.,'Smith')]")  
                // var listTitles =  root.selectNodes("//description"); 
                var listTitles = root.selectNodes("//products[description = '" + search +
                "' or brand = '" +
                search +
                "']");
                var nodeTitle;
                
                alert('Lets search for an item:' + search);
                alert(listTitles.length);
                return;
                var hitCount = 0;
                for (var i = 0; i < listTitles.length; ++i) {
                
                    nodeTitle = listTitles.item(i); //here we specify item index
                    if (nodeTitle.text == search) {
                        //setTextContent(document.all.id, bullet + );
                        //alert('Found! '+ nodeTitle.text)
                        hitCount++;
                        var id = i;
                        var idNodes = root.selectNodes("//products/productid");//[productid="+id+"]");
                        status.innerHTML += '<a class="field" href="products.html?id=' + id + '" >[' + id + ']</a><br>';
                        //alert(idNodes.item(i).text);
                        if (hitCount >= 20) 
                            break;
                        //var bullet = '(' + (i + 1) + ')';
                        //setTextContent(document.all.id, bullet + nodeTitle.text);
                    }
                    
                }
                return;
                
                
                for (var i = 0; i < recentPhrases.length; ++i) {
                    var id = 'phrase' + i;
                    status.innerHTML += '<span id="' + id + '"></span><br>';
                    var bullet = '(' + (i + 1) + ')';
                    setTextContent(document.all.id, bullet + recentPhrases[i]);
                }
            }
            
            function Load(){
                var pidT = document.all.pid;
                var id = pidT.value;
                
                var rs = db.execute('select * from product where id=' + id);
                var index = 0;
                
                var upcT = document.all.upc;
                var descriptionT = document.all.description;
                var brandT = document.all.brand;
                var modelT = document.all.model;
                var typeT = document.all.type;
                var quantityT = document.all.quantity;
                var orderedT = document.all.ordered;
                var costT = document.all.cost;
                var priceT = document.all.price;
                
                while (rs.isValidRow()) {
                
                    upcT.value = rs.field(1);
                    descriptionT = rs.field(2);
                    brandT.value = rs.field(3);
                    modelT.value = rs.field(4);
                    quantityT.value = rs.field(6);
                    orderedT.value = rs.field(7);
                    costT.value = rs.field(8);
                    priceT.value = rs.field(9);
                    loadProductTypes(rs.field(5));
                    
                    rs.next();
                }
                rs.close();
            }
            
            function LoadX(){
                var pidT = document.all.pid;
                var id = pidT.value;
                
                var upcT = document.all.upc;
                var descriptionT = document.all.description;
                var brandT = document.all.brand;
                var modelT = document.all.model;
                var typeT = document.all.type;
                var quantityT = document.all.quantity;
                var orderedT = document.all.ordered;
                var costT = document.all.cost;
                var priceT = document.all.price;
                
                var xmlDoc;
                xmlDoc = loadXMLDoc("products.xml");
                y = xmlDoc.getElementsByTagName("products");
                for (i = 0; i < y.length; i++) {
                    x = y[i].childNodes; //a specific product
                    //if(i<3)
                    //alert( x[3].childNodes[0].nodeValue);
                    if (x[1].childNodes[0].nodeValue == id) //check if matches an id
                    {
                        //alert( x[2].childNodes[0].nodeValue);
                        upcT.value = x[15].childNodes[0].nodeValue;
                        descriptionT.value = x[3].childNodes[0].nodeValue;
                        brandT.value = x[5].childNodes[0].nodeValue;
                        modelT.value = x[7].childNodes[0].nodeValue;
                        quantityT.value = x[11].childNodes[0].nodeValue;
                        orderedT.value = x[13].childNodes[0].nodeValue;
                        costT.value = x[17].childNodes[0].nodeValue;
                        priceT.value = x[19].childNodes[0].nodeValue;
                        loadProductTypes(x[9].childNodes[0].nodeValue);
                        /*
                         <productid>1</productid>
                         <description>Cuenta</description>3
                         <brand>Abono</brand>5
                         <model>Cuenta</model>7
                         <typeid>ABO</typeid>9
                         <qty>0</qty>11
                         <order>0</order>13
                         <upc>Abono</upc>15
                         <cost>0</cost>17
                         <priceA>0</priceA>19
                         <priceB>0</priceB>21
                         <status>1</status>23
                         */
                        break;
                    }
                    else 
                        document.all.status.innerHTML = 'Searching...' + i;
                    
                }
                
            }
            
            function LoadXPIE(){
                var pidT = document.all.pid;
                var id = pidT.value;
                
                var upcT = document.all.upc;
                var descriptionT = document.all.description;
                var brandT = document.all.brand;
                var modelT = document.all.model;
                var typeT = document.all.type;
                var quantityT = document.all.quantity;
                var orderedT = document.all.ordered;
                var costT = document.all.cost;
                var priceT = document.all.price;
                
                //alert('vars ok:' + pidT.value);
                loadTitle2();
                return;
                var xmlDoc;
                
                xmlDoc = loadXMLDoc("products.xml");
                alert('load ok');
                y = xmlDoc.getElementsByTagName("products");
                //alert()
                for (i = 0; i < y.length; i++) {
                    x = y[i].childNodes; //a specific product
                    if (i < 3) 
                        alert(x[3].childNodes[0].nodeValue);
                    if (x[1].childNodes[0].nodeValue == id) //check if matches an id
                    {
                        //alert( x[2].childNodes[0].nodeValue);
                        upcT.value = x[15].childNodes[0].nodeValue;
                        descriptionT.value = x[3].childNodes[0].nodeValue;
                        brandT.value = x[5].childNodes[0].nodeValue;
                        modelT.value = x[7].childNodes[0].nodeValue;
                        quantityT.value = x[11].childNodes[0].nodeValue;
                        orderedT.value = x[13].childNodes[0].nodeValue;
                        costT.value = x[17].childNodes[0].nodeValue;
                        priceT.value = x[19].childNodes[0].nodeValue;
                        loadProductTypes(x[9].childNodes[0].nodeValue);
                        /*
                         <productid>1</productid>
                         <description>Cuenta</description>3
                         <brand>Abono</brand>5
                         <model>Cuenta</model>7
                         <typeid>ABO</typeid>9
                         <qty>0</qty>11
                         <order>0</order>13
                         <upc>Abono</upc>15
                         <cost>0</cost>17
                         <priceA>0</priceA>19
                         <priceB>0</priceB>21
                         <status>1</status>23
                         */
                        break;
                    }
                    //else 
                    //document.getElementById("status").innerHTML = 'Searching...' + i;
                
                }
                
            }
            
            function loadProductTypes(sel){
                var rs = db.execute('select * from ProductType order by 2 desc');
                var index = 0;
                var ptypespan = document.all.ptypespan;
                var itext = '';
                itext += '<select name="producttype">';
                while (rs.isValidRow()) {
                    itext += '<option value="' + rs.field(0) + '"';
                    if (sel == rs.field(0)) 
                        itext += ' selected ';
                    itext += '>' + rs.field(1) + '</option>';
                    rs.next();
                }
                rs.close();
                itext += '</select>';
                //alert(itext);
                ptypespan.innerHTML = itext;
                
            }
            
            function AddOne(control, amount){
                var amount1 = new Number(amount);
                var amount2 = new Number(document.all(control).value);
                var result = amount1 + amount2;
                
                document.all(control).value = result;
            }
        </script>
    </body>
</html>
